import { Textarea } from 'ant-design-vue';
import { defineComponent, PropType, ref } from 'vue';
import { QuestionType } from '../typing';

export default defineComponent({
  props: {
    question: {
      type: Object as PropType<QuestionType>,
      required: true,
    },
    language: {
      type: String as PropType<'zh' | 'en'>,
      required: true,
    },
  },
  setup(props) {
    const { language, question } = props;
    const mode = ref<string>(question.mode);
    const questionProper =
      language === 'zh' ? question.questionProperZh : question.questionProperEn;

    const errorMessage = ref('');
    const lastInputString = ref('');

    const checkInputValue = () => {
      if (questionProper?.shortAnswerItem?.isWordLimit) {
        const minCharCount =
          questionProper.shortAnswerItem.minCharCount === undefined
            ? 0
            : questionProper.shortAnswerItem.minCharCount;
        const maxCharCount =
          questionProper.shortAnswerItem.maxCharCount === undefined
            ? 0
            : questionProper.shortAnswerItem.maxCharCount;
        if (question.value !== undefined) {
          if (question.value.length < minCharCount) {
            if (language === 'zh') {
              errorMessage.value = `最少输入${minCharCount}个字符`;
            } else if (language === 'en') {
              errorMessage.value = `At least ${minCharCount} inputs are required`;
            }
            question.value = lastInputString.value;
          } else if (question.value.length > maxCharCount) {
            if (language === 'zh') {
              errorMessage.value = `输入的字符不能超过${maxCharCount}个`;
            } else if (language === 'en') {
              errorMessage.value = `The input characters cannot exceed ${maxCharCount}`;
            }
            question.value = lastInputString.value;
          } else {
            errorMessage.value = '';
            lastInputString.value = question.value;
          }
        }
      }
    };

    return () => {
      if (question.value !== undefined) {
        checkInputValue();
      }
      return (
        <div
          class={[
            'question-container',
            'question-answer-container',
            { 'question-design': mode.value === 'design' },
          ]}
        >
          <div class="question-title" v-html={questionProper!.title}></div>
          <div class="question-items">
            <Textarea
              v-model:value={question.value}
              style="height:100px"
              showCount={questionProper?.shortAnswerItem?.isWordLimit}
              onChange={checkInputValue}
              onBlur={checkInputValue}
            />
          </div>
          <div style="color:#f81d22;font-size:14px;margin-top:5px">{errorMessage.value}</div>
        </div>
      );
    };
  },
});
